﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;
using WChat;
using System.IO;
using System.Net;
using System.Threading;
using Aliyun.OSS.Samples;
using Aliyun.OSS.Common;
using System.Security.Cryptography;
using HuanQiuCrm.Properties;
using Newtonsoft.Json.Linq;

namespace HuanQiuCrm {
    public partial class loginwx : Skin_DevExpress {
        public static event logineventhander Login;
        public delegate void logineventhander( Image lgrseult );
        LoginService ls = new LoginService();
        public static Bitmap img_bit = null;
        public static object login_result = null;
        private bool isclose = false;
        private bool clicklogin = false;
        Settings st = new Settings();
        SqlHandle sql = new SqlHandle();
        public static List<Bitmap> headpic = new List<Bitmap>();
     
        private bool openwebwx = false;
        private static int f = 0;
        public static String TITLE = "通知";
        public static String ALERT = "";
        public static String MSG_CONTENT = "Test from C# v3 sdk - msgContent---.NET3.5";
        public static String app_key = "91894304d21467355a6ad9a8";
        private static string getdata = DateTime.Now.ToString();
        private static string ftpUser = "lidaliang2016";
        private static string ftpPwd = "A8F3738D49ffc9";
        private static string path = "D:/Documents/HuanQiuYunKong";
        public static String master_secret = "db72c7f2847ff6297d4e092f";

        private string login_path = WChat.path.paths + "\\login.txt";   //工作时的路径
        private string icon_path = WChat.path.paths + "\\login_icon.jpg";   //工作时的路径
        private string uin_path = WChat.path.paths + "\\MyUin.txt";   //工作时的路径
        private string nic_path = WChat.path.paths + "\\MyNick.txt";   //工作时的路径

        public loginwx() {
            InitializeComponent();
            Pqrcode.Image = null;
            Pqrcode.SizeMode = PictureBoxSizeMode.Zoom;
            lblTip.Location = new Point(55, 250);
            lblTip.Text = "手机微信扫一扫以登录";
        }

        public void DoLogin() {
            Pqrcode.Image = null;
            Pqrcode.SizeMode = PictureBoxSizeMode.Zoom;
            lblTip.Text = "手机微信扫一扫以登录";

            ((Action)(delegate () {
                LoginService ls = new LoginService();
                Image qrcode = ls.GetQRCode();       //异步加载二维码
                if (qrcode != null) {
                    Pqrcode.Image = qrcode;
                    while (!isclose)  //循环判断手机扫面二维码结果
                    {
                        login_result = ls.LoginCheck();
                        Thread.Sleep(5);
                        if (login_result is Image) {                  //已扫描 未登录
                        this.BeginInvoke((Action)delegate () {
                            lblTip.Text = "请点击手机上登录按钮";
                            Pqrcode.SizeMode = PictureBoxSizeMode.CenterImage;  //显示头像
                            Pqrcode.Image = login_result as Image;
                            img_bit = login_result as Bitmap;
                        });
                       }
                        Thread.Sleep(5);
                        if (login_result is string && img_bit!= null) {
                            WriteLog.Writelog("login_result为字符串，登录完成准备初始化", login_result as string);
                            ls.GetSidUid(login_result as string);
                            headpic.Add(img_bit);  //登录成功了再将用户头像存入数组，防止出错         
                            this.BeginInvoke((Action)delegate () {                    
                            Login?.Invoke(img_bit);
                            this.Close();
                        });
                        break;    //登录完成后跳出循环
                    }
                }
                 }
             })).BeginInvoke(null, null);
        }

        private void loginwx_Load(object sender, EventArgs e) {
            GetMyDevices();
            if (File.Exists(login_path) && File.Exists(uin_path)&& File.Exists(nic_path)) {
                if (File.Exists(icon_path)) {
                    Pqrcode.SizeMode = PictureBoxSizeMode.CenterImage;  //显示头像
                    Pqrcode.Image = new Bitmap(icon_path);
                    clicklogin = true;
                    this.btn_login.Visible = true;
                    lblTip.Location = new Point(70, 250);
                    lb_autos_can.Visible = false;
                    lblTip.Text = Form1.ReadLogin(nic_path).Length > 9 ? Form1.ReadLogin(nic_path).Substring(0, 9) : Form1.ReadLogin(nic_path);
                }
            }else {
                this.btn_login.Visible =false;
                this.lb_swich.Text = "刷新二维码";
                DoLogin();
            }
        }
        /// <summary>
        /// 免扫码登陆
        /// </summary>
        /// <param name="cookie_file"></param>
        /// <param name="_uin"></param>
        private void login_again( string cookie_file, string _uin ) {
            string uuid = string.Empty;
            JObject result = null;
            string Uin = Form1.ReadLogin(_uin);
            ((Action)(delegate () {
            WXService wxs = new WXService();
            result = wxs.ClickLogin(Form1.ReadLogin(cookie_file), Uin);
            if (result != null) {
                if (result["ret"].ToString() == "0" && result["msg"].ToString() == "all ok") {
                    uuid = result["uuid"].ToString();
                    if (uuid != string.Empty) {
                        while (!isclose) {
                            login_result = ls.ClickLoginCheck(uuid);
                            if (login_result is Image) //已扫描 未登录
                            {
                                this.BeginInvoke((Action)delegate () {
                                    lblTip.Text = "请点击手机上登录按钮";
                                    this.btn_login.Visible = false;
                                    Pqrcode.SizeMode = PictureBoxSizeMode.CenterImage;  //显示头像
                                    Pqrcode.Image = login_result as Image;
                                    img_bit = login_result as Bitmap;
                                });
                            }
                            if (login_result is string) {
                                WriteLog.Writelog("login_result为字符串，登录完成准备初始化", login_result as string);
                                ls.GetSidUid(login_result as string);
                                headpic.Add(img_bit);  //登录成功了再将用户头像存入数组，防止出错         
                                this.BeginInvoke((Action)delegate () {
                                    Login?.Invoke(img_bit);
                                    this.Close();
                                });
                                break;    //登录完成后跳出循环
                            }
                        }
                    }
                 } else {
                     MessageBox.Show("设备验证失败，请稍后重试!");
                 }
             } else {
                 MessageBox.Show("Cookie错误，请扫二维码登录!");
             }
            
         })).BeginInvoke(null, null);
        }

        private void loginwx_FormClosed(object sender, FormClosedEventArgs e) {
            isclose = true;
            headpic.Remove(login_result as Bitmap);  //67, 251 50, 250关闭时将用户头像移除数组，防止出项红叉问题        
        }
        /// <summary>
        /// 刷新二维码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void skinLabel1_Click(object sender, EventArgs e) {
            this.btn_login.Visible = false;
            lblTip.Location = new Point(50, 250);
            this.lb_swich.Text = "刷新二维码";
            lb_autos_can.Visible = true;
            DoLogin();
        }
      
        private void btn_login_Click( object sender, EventArgs e ) {
            if (clicklogin) {
                login_again(login_path, uin_path);  //二次免扫码登录
                clicklogin = false;
            }
            if (openwebwx) {
                string time = DateTime.Now.ToString("yyyyMMddHHmmss");
                string qrcode_path = WChat.path.paths + "\\" + time + "qrcode.jpg";
                string qrcode_nam = time + "qrcode.bmp";
                string mess = 0 + "|" + qrcode_nam;
                if (CB_phone.Text != string.Empty) {
                    try {
                        Pqrcode.Image.Save(qrcode_path);     //下载图片,并保存到特定位置
                        f = f + 1;
                    }
                    catch (Exception ex) {
                        MessageBox.Show(ex.ToString());
                    }
                    UploadFileToOss("lidaliang2016", qrcode_nam, qrcode_path);
                    PushAndroidAll(mess, CB_phone.Text);
                }  else {
                    MessageBox.Show("请先在下拉列表选择要登陆的微信！", " 环球云提示");
                }
            }
        }

        #region 自动登录用代码

        #region 极光推送
        public void PushAndroidAll( string message, string tag ) {
            try {
                Random ran = new Random();
                int sendno = ran.Next(1, 2100000000);//随机生成的一个编号
                //string app_key = app_key;
                string masterSecret = master_secret;
                int receiver_type = 2;//接收者类型。2、指定的 tag。3、指定的 alias。4、广播：对 app_key 下的所有用户推送消息。5、根据 RegistrationID 进行推送。当前只是 Android SDK r1.6.0 版本支持
                // string receiver_value = REGISTRATION_ID;
                int msg_type = 2;//1、通知2、自定义消息（只有 Android 支持）
                string themsg_content = "{\"n_builder_id\":\"00\",\"n_title\":\"" + TITLE + "\",\"n_content\":\"" + MSG_CONTENT + "\"}";//消息内容
                string mymsg_content = "{\"message\":\"" + message + "\"}";   //自定义消息
                string platform = "android";//目标用户终端手机的平台类型，如： android, ios 多个请使用逗号分隔。
                string verification_code = GetMD5Str(sendno.ToString(), receiver_type.ToString(), tag, masterSecret);//验证串，用于校验发送的合法性。MD5
                string postData = "sendno=" + sendno;
                postData += ("&app_key=" + app_key);
                postData += ("&masterSecret=" + masterSecret);
                postData += ("&receiver_type=" + receiver_type);   //接收者类型
                postData += ("&receiver_value=" + tag);           //类型值
                postData += ("&msg_type=" + msg_type);
                postData += ("&msg_content=" + mymsg_content);
                postData += ("&platform=" + platform);
                postData += ("&verification_code=" + verification_code);
                //byte[] data = encoding.GetBytes(postData);
                byte[] data = Encoding.UTF8.GetBytes(postData);
                string resCode = GetPostRequest(data);//调用极光的接口获取返回值
                JpushMsg msg = Newtonsoft.Json.JsonConvert.DeserializeObject<JpushMsg>(resCode);//定义一个JpushMsg类，包含返回值信息，将返回的json格式字符串转成JpushMsg对象
            }
            catch (Exception ex) {
                MessageBox.Show(ex.ToString());
            }
        }  //推送自定义消息
        public string GetMD5Str( params string[] paras ) {
            string str = "";
            for (int i = 0; i < paras.Length; i++) {
                str += paras[i];
            }
            byte[] buffer = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(str));
            string md5Str = string.Empty;
            for (int i = 0; i < buffer.Length; i++) {
                md5Str = md5Str + buffer[i].ToString("X2");
            }
            return md5Str;
        }
        public string GetPostRequest( byte[] data ) {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://api.jpush.cn:8800/v2/push");

            myRequest.Method = "POST";//极光http请求方式为post
            myRequest.ContentType = "application/x-www-form-urlencoded";//按照极光的要求
            myRequest.ContentLength = data.Length;
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            // Get response
            var response = (HttpWebResponse)myRequest.GetResponse();
            using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"))) {
                string result = reader.ReadToEnd();
                reader.Close();
                response.Close();
                return result;
            }
        }
        public class JpushMsg {
            private string sendno;//编号

            public string Sendno {
                get { return sendno; }
                set { sendno = value; }
            }
            private string msg_id;//信息编号

            public string Msg_id {
                get { return msg_id; }
                set { msg_id = value; }
            }
            private string errcode;//返回码

            public string Errcode {
                get { return errcode; }
                set { errcode = value; }
            }
            private string errmsg;//错误信息

            public string Errmsg {
                get { return errmsg; }
                set { errmsg = value; }
            }
        }
        #endregion

        private void GetMyDevices() {
            string account = st.Admin;
            for (int i = 0; i < sql.SelecUserdevices(account).Count; i++) {
                CB_phone.Items.Add(sql.SelecUserdevices(account)[i].Trim());
            }
        }

        private void getmywx() {
            //   string account = "胡瑞荣1";
            string account = st.UseAcct;
            for (int i = 0; i < sql.Select_Num_Wx(account).Count; i++) {
                if (sql.Select_Num_Wx(account)[i].Trim()!=string.Empty) {
                    CB_phone.Items.Add(sql.Select_Num_Wx(account)[i].Trim());
                }
            }
        }

        private static void UploadFileToOss( string bucketName, string filename, string path ) {
            try {
                CreateBucketSample.CreateBucket(bucketName);
                PutObjectSample.PutObject(bucketName, filename, path);
            }
            catch (OssException ex) {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        /// <summary>
        /// 测试代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click( object sender, EventArgs e ) {
            int sd = 1;
            string device;
            for (int i = 0; i < 100; i++) {
                device = "hrrhq" + sd.ToString();
                sd++;
                sql.AddDevice("lsyh40", device);
            }
             MessageBox.Show("添加完成");
        }
        /// <summary>
        /// 自动扫
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lb_autos_can_Click( object sender, EventArgs e ) {
            CB_phone.Visible = true;
            this.btn_login.Visible = true;
            clicklogin = false;
            openwebwx = true;
        }
    }
}
